<template>
  <el-aside :width="isCollapse ? '64px' : '200px'">
    <el-scrollbar wrap-class="scrollbar-wrapper">
      <el-menu
        :default-active="activeMenu"
        background-color="#001529"
        text-color="#bfcbd9"
        active-text-color="#409EFF"
        unique-opened
        router
      >
        <sidebar-item 
          v-for="route in permissionRoutes"
          :key="route.path"
          :item="route"
          :base-path="route.path" 
        />
      </el-menu>
    </el-scrollbar>
  </el-aside>
</template>

<script setup>
import { computed, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import SidebarItem from './SidebarItem.vue'
import { usePermissionStore } from '@/stores/permission'

const permissionStore = usePermissionStore()
const route = useRoute()
// 修改权限路由过滤逻辑（第23-32行）
const permissionRoutes = computed(() => {
  const filterRoutes = (routes) => {
    return routes.filter(route => {
      const hasValidChildren = route.children?.some(child => !child.meta?.hidden)
      return !route.meta?.hidden && 
        (hasValidChildren || route.component)
    }).map(route => ({
      ...route,
      children: route.children ? filterRoutes(route.children) : []
    }))
  }
  return filterRoutes(permissionStore.routes)
})

// 添加路由加载异常处理
onMounted(async () => {
  try {
    if (permissionStore.routes.length === 0) {
      await permissionStore.generateRoutes()
    }
  } catch (error) {
    console.error('路由加载失败:', error)
  }
})

// 当前激活菜单
const activeMenu = computed(() => {
  const { meta, path } = route
  return meta.activeMenu || path
})

// 侧边栏折叠状态，从外部传入
const props = defineProps(['isCollapse'])
</script>

<style scoped>
.sidebar-container {
  background: #001529;
  transition: width 0.3s;
}
</style>